<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
         <el-button type="text" @click.stop="open(scope.row)">开始学习</el-button>
      </template>

    </avue-crud>
      <el-dialog title="课程学习" :visible.sync="dialogTableVisible" :modal-append-to-body="false" :fullscreen="true" :before-close="handleClose">

        <el-row :gutter="20">
          <el-col :span="4">

            <div class="bg-purple" :style="{height:height+ 'px'}">
              <div style="text-align:left;">
                <h3 style="margin:0px;">课程学习</h3>
                <div>累计学习时长：{{hour}}时{{minute}}分{{second}}秒</div>
              </div>
                <div v-for="item in courseware" @click="show(item)">
                  <div v-show="item.wjlx==1">
                    <img src="/img/bg/pdf.png">
                  </div>
                  <div v-show="item.wjlx==2">
                    <img src="/img/bg/mp4.png">
                  </div>
                  <span>{{ item.zlbt }}</span>
                </div>
            </div>
          </el-col>
          <el-col :span="20">
           <div class="bg-purple" :style="{height:height+ 'px'}">
              <template v-show="fileType==1">
                <div class="pdf" v-show="fileType ==1" :style="{height:height+ 'px'}">
                  <iframe :src="src" frameborder="0" style="width: 100%; height: 100%"></iframe>
                </div>
                <div v-show="fileType ==2" style="position: relative" >
                  <LivePlayer aspect="16:8" :videoUrl="videoUrl" fluent autoplay live stretch="false"></LivePlayer>
                </div>
              </template>
            </div>
          </el-col>
        </el-row>
      </el-dialog>
  </basic-container>

</template>



<script>
  import {getList, getDetail, add, update, remove} from "@/api/jypx/educourse/course";
  import {mapGetters} from "vuex";
  import request from '@/router/axios';
  import pdf from 'vue-pdf'
  import LivePlayer from "@liveqing/liveplayer";
  import website from "@/config/website";

  export default {
    components: {pdf,LivePlayer},
    data() {
      return {
        height: `${document.documentElement.clientHeight-120}`,
        videoUrl:'',
        currentPage: 0,
        pageCount: 0,
        fileType: 0,
　　　　　src: '',
        currentItem:null,
        courseware:[],
        file:{},
        dialogTableVisible: false,
        courseId:0,
        totalSecond:0,
        hour:0,
        minute:0,
        second:0,
        timer:null,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: false,
          addBtn: false,
          viewBtn: false,
          editBtn: false,
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              /*label: "培训类别",
              prop: "pxlb",
              align: "center",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]*/
              label: "培训类别",
              prop: "pxlb",
              type: "select",
              align: "center",
              dataType: "number",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=pxlb",
              props: {
                label: "dictValue",
                value: "dictKey"
              }
            },
            {
              label: "课目名称",
              prop: "kcmc",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "试题数量",
              prop: "stsl",
              align: "center",
              hide: false,
              addDisplay: false,
              editDisplay: true,
              viewDisplay: true,
            },
            {
              label: "课件数量",
              prop: "kjsl",
              align: "center",
              hide: false,
              addDisplay: false,
              editDisplay: true,
              viewDisplay: true,
            },
            {
              label: "课程学时（分）",
              prop: "kcxs",
              align: "center",
              hide: false,
              addDisplay: false,
              editDisplay: true,
              viewDisplay: true,
            },
            {
              label: "已学时长（分）",
              prop: "yxsc",
              align: "center",
              hide: false,
              addDisplay: false,
              editDisplay: true,
              viewDisplay: true,
            },
            /*{
              label: "试题更新时间",
              prop: "kjgxsj",
              align: "center",
              hide: false,
              addDisplay: false,
              editDisplay: true,
              viewDisplay: true,
            },*/
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.course_add, false),
          viewBtn: this.vaildData(this.permission.course_view, false),
          delBtn: this.vaildData(this.permission.course_delete, false),
          editBtn: this.vaildData(this.permission.course_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      changePdfPage (val) {
        if (val === 0 && this.currentPage > 1) {
          this.currentPage--
        }
        if (val === 1 && this.currentPage < this.pageCount) {
          this.currentPage++
        }
      },

      loadPdfHandler () {
        this.currentPage = 1
      },
      open(row) {
        if(row.kjsl<1){
          this.$message({
            message: '暂无课件，请联系培训人员',
            type: 'warning'
          });
          return;
        }else{
          //开始学习
          return request({
            url: '/api/eduStudyRecord/studyrecord/totalTime',
            method: 'post',
            params: {
              courseId:row.id
            }
          }).then(res=>{
            this.dialogTableVisible=true;

            this.load(row.id);
            this.courseId=row.id;
            this.totalSecond=res.data.data;
            console.log("total:"+res.data.data);
            this.hour=parseInt(this.totalSecond/60/60)%24;
            this.minute=parseInt(this.totalSecond/60)%60;
            this.second=parseInt(this.totalSecond%60);
          });
        }
      },
      handleClose(done){
        clearInterval(this.timer);
        this.timer=null;
        if(this.currentItem){
          return request({
            url: '/api/eduStudyRecord/studyrecord/end',
            method: 'post',
            params: {
              courseId: this.courseId,
              coursewareId: this.currentItem.id
            }
          }).then(res => {
          this.currentItem=null;
            this.src="";
            this.videoUrl="";
            done();
            console.log("end studying");
          });
        }else{
        this.currentItem=null;
          this.src="";
          this.videoUrl="";
          done();
        }

      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        this.query.pxlb=1;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      load(courseId){
        let _this=this;
        return request({
            url: '/api/eduCourseware/courseware/listAll',
            method: 'get',
            params: {
              courseId:courseId
            }
          }).then(res=>{
            _this.courseId=courseId;
            _this.courseware = res.data.data;
          });
      },
      loadFile(fileId){
        let _this=this;
        return request({
          url: '/api/fileManager/file/'+fileId,
          method: 'get'
        }).then(res=>{
          _this.file = res.data.data;
        });
      },
      view(item){
        //TODO 计数器
        if(this.timer==null){
          this.timer=setInterval(()=>{
            if(this.second<59){
              this.second++;
            }else{
              this.second=0;
              if(this.minute<59){
                this.minute++;
              }else{
                this.minute=0;
                this.hour++;
              }
            }
          },1000);
        }
        this.fileType=item.wjlx;
        if(item.wjlx==1){
          this.loadFile(item.kcwj).then(()=>{
            if(this.file.fileName.toLocaleLowerCase().indexOf(".pdf")>0){
              //插件法预览PDF
              axios({
                method: 'GET',
                url: '/api/fileManager/download/'+item.kcwj, // 后台接口
                paramsSerializer: function(params) {
                  return qs.stringify(params, { arrayFormat: 'brackets' })
                },
                headers: {
                  'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                },
                responseType: 'blob'
              }).then(response => {
                let urlPdf  = window.URL.createObjectURL(new Blob([response.data]))
                console.log('urlPdf',urlPdf) //blob:http://localhost:8080/e8451cb8-3238-4272-b490-0420df4a5b88
                this.src = '/pdf/web/viewer.html?file=' + encodeURIComponent(urlPdf)
              }).catch(error => { this.$message.error('' + error) });
            }else{
              this.src=this.website.fileViewServer+'/onlinePreview?url='+encodeURIComponent(Base64.encode(this.file.fileUrl));
            }
            // this.src=this.website.fileViewServer+'/onlinePreview?url='+encodeURIComponent(Base64.encode(this.file.fileUrl));
          });

        }else if(item.wjlx==2){
          this.videoUrl=item.kcsp;
        }
      },
      show(item){
        if(this.currentItem==null) {
          return request({
            url: '/api/eduStudyRecord/studyrecord/start',
            method: 'post',
            params: {
              courseId: this.courseId,
              coursewareId: item.id
            }
          }).then(res => {
            this.currentItem=item;
            console.log("start studying");
            this.view(item);
          });
        }else{
          return request({
            url: '/api/eduStudyRecord/studyrecord/end',
            method: 'post',
            params: {
              courseId: this.courseId,
              coursewareId: this.currentItem.id
            }
          }).then(res => {
            return request({
              url: '/api/eduStudyRecord/studyrecord/start',
              method: 'post',
              params: {
                courseId: this.courseId,
                coursewareId: item.id
              }
            }).then(res => {
              this.currentItem=item;
              console.log("start studying");
              this.view(item);
            });
          });
        }


      }


    }
  };
</script>

<style>
.msgbox {
  width: 100%;
}
@media screen and (min-width: 768px) {
  .msgbox {
    width: 99%;
    height: 96%;
  }
}
.el-dialog__body{
  padding: 10px 20px;
}
.bg-purple{
  padding:10px;text-align:center;
  border-radius: 4px;
  background: #d3dce6;
}
</style>
